var yaGrid=new Class({
    Implements:Options,
    options:{
        ignoreClass:'header',
        checkAll:'effectAll',
        checkboxFilter:'input[name=\'sid[]\']',
        style:{
            hover:'rowHover',
            checked:'rowChecked'
        }
    },
    initialize:function(dataSource,options){
        this.rows=$(dataSource).getElements('tbody tr[class!='+this.options.ignoreClass+']');
        if (this.rows.length==0) return;
        if(options) this.setOptions(options);
        this.rows.each(function(row){
            row.addEvents({
                'mouseover':function(){
                    if(!row.hasClass(this.options.style.checked)){
                        row.addClass(this.options.style.hover);
                    }
                    if(this.options.rowMouseover){
                        this.options.rowMouseover.run(this,row);
                    }
                }.bind(this),
                'mouseout':function(){
                    if(!row.hasClass(this.options.style.checked)){
                        row.removeClass(this.options.style.hover);
                    }
                    if(this.options.rowMouseout){
                        this.options.rowMouseout.run(this,row);
                    }
                }.bind(this),
                'click':function(){
                    this.toggleRowChecked(row);
                }.bind(this)
            });
            //checkbox filter
            var ips=row.getElement(this.options.checkboxFilter);
            if(ips){
                row.store('cb',ips);
                if(true==ips.getProperty('checked')){
                    row.addClass(this.options.style.rowChecked);
                }else{
                    row.removeClass(this.options.style.rowChecked);
                }
                ips.addEvent('click',function(event){
                    ips.setProperty('checked',(ips.getProperty('checked'))?false:true);
                });
            }
        },this);
        //select/disselect all
        var effectAll=$(this.options.checkAll);
        if(effectAll){
            effectAll.addEvent('click',function(){
                this.toggleAllRowsChecked(effectAll);
            }.bind(this));
        }
    },
    toggleRowChecked:function(row){
        var cb=row.retrieve('cb');
        if( !cb) return;
        if(cb.getProperty('checked')){
            this.unCheckRow(row,cb);
        }else{
            this.checkRow(row,cb);
        }
    },
    unCheckRow:function(row,cb){
        cb=cb || row.retrieve('cb');
        cb.setProperty('checked',false);
        row.removeClass(this.options.style.checked);
    },
    checkRow:function(row,cb){
        cb=cb || row.retrieve('cb');
        cb.setProperty('checked',true);
        row.addClass(this.options.style.checked);
    },
    toggleAllRowsChecked:function(effectAll){
        if(effectAll.getProperty('checked')){
            this.rows.each(function(row){
                this.checkRow(row);
            },this);
        }else{
            this.rows.each(function(row){
                this.unCheckRow(row);
            },this);
        }
    },
    getChecked:function(){
        var c=0,str=[];
        this.rows.each(function(row){
            var cb=row.retrieve('cb');
            if(cb.getProperty('checked')){
                c++;
                str.push(cb.getProperty('value'));
            }
        });
        return {'count':c,'value':str.join(',')};
    }
});

/**
 * 表单检查函数
 */
function checkform(fm,validates){
    var eles=fm.elements;
    var passValidate=true;
    validates.each(function(validate){
        var ele=$(eles[validate[0]]);
        if(ele){
            var val='',rules=validate[1];
            if('select'==ele.get('tag')){ val=ele.options[ele.selectedIndex].value; }
            else { val=ele.getProperty('value').trim(); }
            for(var i=0,len=rules.length;i<len;i++){
                var vaitem=rules[i],show=true,msg=vaitem.msg,type='error';
                var when=vaitem.when || null;
                if(when=='notnull' && val==''){
                    cf_hideTip(ele);
                    continue;
                }
                switch(vaitem.rule){
                    case 'required':if(val.length==0) show=false;break;
                    case 'id':if(!val.test('^[1-9]\d*$')) show=false;break;
                    default:if(!val.test(vaitem.rule)) show=false;
                }
                if(show){
                    cf_hideTip(ele);
                }else{
                    passValidate=false;
                    cf_showTip(ele,msg,type);
                    break;  //一次检查未通过，则跳过该元素的检查
                }
            }
        }
    });
    return passValidate;
}
function cf_showTip(ele,msg,type){
    var div=ele.getPrevious('.vatip:first-child');
    if(!div){
        div=new Element('div',{'class':'vatip','styles':{'display':'none'}});
        div.inject(ele,'before');
    }
    type=type || 'error';
    if(type=='error'){
        div.set('html','<span>'+msg+'</span>');
    }
    div.setStyle('display','block');
}
function cf_hideTip(ele){
    var div=ele.getPrevious('.vatip:first-child');
    if(div){
        div.setStyle('display','none');
    }
}

var app=new Hash();

/**
 * 表单响应
 * opts参数:
 *   rows:'n'必须选中n行，'n,'至少选中n行，'n,m'至少n行，至多m行,默认至少要选中
 *   一行
 *   rowsMsg:不符合rows限制时的提示消息
 *   url:表单提交的地址
 *   form:表单,没有指定此项将自动取页面上的第一项为表单
 *   tableId:指定grid的ID，没有此项则默认以gridInst代替
 *   submitType:表单提交方式：ajax,custom，不指定则为默认提交方式。当为custom时
 *   ，将调用custom_submit()方法,方式为ajax时可以再传入ajaxOptions，作为ajax的参
 *   数
 */
function defEdit(){
    doAction('edit',{submitType:'get'});
}
function doAction(actionType,options){
    if('back'==actionType || 'historyBack'==actionType){
        //window.history.back();
        top.pageBack();
    }else{
        var opts=options || {};
        var fm=$(opts.form || document.forms[0]);
        fm.elements['a'].value=actionType;
        var rows=opts.rows || '1,';
        var limits=rows.split(',');
        var tableId=opts.tableId || 'gridInst',checkedInfo;
        if(app.has(tableId)){
            checkedInfo=(app.get(tableId)).getChecked();
            //暂时只考虑至少选中的情况
            if(checkedInfo.count<limits[0]){
                alert(opts.rowsMsg||'请先选择记录');
                return;
            }
        }
        if(typeof(_validate)!='undefined' && ! checkform(fm,_validate)){
            return;
        }
        if(typeof(before_submit)=='function'){
            if(!before_submit()) return;
        }
        var submitType=opts.submitType || 'post';
        if(submitType=='post'){
            fm.submit();
        }else if(submitType=='custom'){
            custom_submit(fm,actionType,options);
        }else if(submitType=='ajax'){
            var ao=opts.ajaxOptions || {};
            fm.set('send',{
                url:ao.url || fm.getAttribute('action')+'/'+actionType,
                method:'post',
                onRequest:function(){
                    if(ao.onRequest){
                        ao.onRequest();
                    }else{
                        top.showMsg( ao.runningMsg || '正在将信息保存到服务器，请等候',{type:'running'});
                    }
                },
                onSuccess:function(txt){
                    var json=JSON.decode(txt);
                    if(ao.onSuccess){
                        ao.onSuccess(json);
                    }else{
                        var msg;
                        if(json.result=='success'){
                            msg=ao.successMsg ||json.msg|| '操作成功';
                        }else{
                            msg=ao.failureMsg ||json.msg || '操作失败';
                        }
                        top.showMsg(msg,{type:json.result,disappear:1,onDisappear:function(){
                            top.fixedMsg(json.result,msg);
                            if(ao.callback){
                                ao.callback(json.result,json);
                            }
                        }});
                    }
                },
                onFailure:function(){
                    if(ao.onFailure){
                        ao.onFailure();
                    }else{
                        top.showMsg('与服务器通信失败',{type:'failure',clickclose:true});
                    }
                }
            });
            fm.send();
        }else if(submitType=='get'){
            //暂时只考虑表单里只有sid和a的情况
            window.location=fm.getProperty('action')+'/'+actionType+'/sid/'+checkedInfo.value;
        }
    }
}

$(window).addEvents({
    'domready':function(){
        //为输入型控件附加效果
        var ips=$$('input[type=text]','input[type=password]','textarea');
        ips.each(function(ele){
            ele.setProperties({
                'class':'textInput',
                'autocomplete':'off'
            });
            ele.addEvents({
                'focus':function(){
                    this.setProperty('class','textInputFocus');
                },
                'blur':function(){
                    this.setProperty('class','textInput');
                }
            });
        });
        if(ips.length>0){
            ips[0].focus();
        }
        //创建数据网格
        $$('table.data').each(function(grid,gridIndex){
            var idstr=(grid.id) ? grid.id : '__g_'+gridIndex;
            var gridOpt={};
            if(typeof _gridOptions !='undefined'){
                gridOpt=_gridOptions;
            }
            app.set(idstr,new yaGrid(grid,gridOpt));
        });
        //事件回调
        if(typeof onDomready =='function'){
            onDomready();
        }
        if(typeof searchOpts !== 'undefined'){
            top.registerSearch(searchOpts);
        }
        //top.addURLHistory(window.location.href);//保存历史记录
    }
});

/**
 * tools
 */
function setSelectOption(selectEle,val){
    var opt=$(selectEle).getElement('option[value='+val+']');
    if(opt){
        opt.selected=true;
    }
}

/**
 * 高亮关键字
 * words:要高亮的关键字(多个关键字则以数组形式传入)
 * opts.selector:DOM选择器，即在哪个范围内搜索关键词
 * opts.nodeName:胜于包裹关键词的元素名称，默认为span
 * opts.className：上条所指元素的class，默认为highlight
 *
 */
function highlight(words,options){
    if($type(words)=='string'){
        words=[words];
    }
    var opts=options || {};
    var flag=opts.caseSensitive ? '' : 'i';
    var pattern='('+words.join('|')+')';
    if(opts.wordsOnly){
        pattern='\\b'+pattern+'\\b';
    }
    var re=new RegExp(pattern,flag);
    $(window).addEvent('domready',function(){
        $$( opts.selector || document.body ).each(function(node){
            _highlight(node,re,opts.nodeName || 'span',opts.className || 'highlight');
        });
    });
}
function _highlight(node,re,nodeName,className){
    if(node.nodeType===3){
        var match=node.data.match(re);
        if(match){
            var hl=new Element(nodeName,{'class':className});
            var wordNode=node.splitText(match.index);
            wordNode.splitText(match[0].length);
            hl.appendChild(wordNode.cloneNode(true));
            wordNode.parentNode.replaceChild(hl,wordNode);
            return 1;
        }
    }else if(node.nodeType===1 && node.childNodes && !/(script|style)/i.test(node.tagName) && ! ( node.tagName===nodeName.toUpperCase() &&node.className === className )){
        var nodes=node.childNodes;
        for(var i=0,len=nodes.length;i<len;i++){
            i+=_highlight(nodes[i],re,nodeName,className);
        }
    }
    return 0;
}
